#!/bin/bash

# Bai-hu Cloud Platform 开发环境设置脚本

set -e

echo "🚀 Setting up Bai-hu Cloud Platform development environment..."

# 检查必需的工具
check_command() {
    if ! command -v $1 &> /dev/null; then
        echo "❌ $1 is not installed. Please install it first."
        exit 1
    fi
}

echo "📋 Checking required tools..."
check_command "node"
check_command "pnpm"
check_command "docker"
check_command "docker-compose"

# 检查 Node.js 版本
NODE_VERSION=$(node -v | cut -d'v' -f2 | cut -d'.' -f1)
if [ "$NODE_VERSION" -lt 18 ]; then
    echo "❌ Node.js version 18 or higher is required. Current version: $(node -v)"
    exit 1
fi

echo "✅ All required tools are available"

# 创建环境变量文件
if [ ! -f "apps/cloud-platform-api/.env" ]; then
    echo "📝 Creating environment configuration..."
    cp apps/cloud-platform-api/.env.example apps/cloud-platform-api/.env
    echo "✅ Environment file created. Please review and update apps/cloud-platform-api/.env"
fi

# 安装依赖
echo "📦 Installing dependencies..."
cd apps/cloud-platform-api
pnpm install

# 启动 Docker 服务
echo "🐳 Starting Docker services..."
cd ../..
docker-compose -f docker-compose.dev.yml up -d

# 等待服务启动
echo "⏳ Waiting for services to be ready..."
sleep 10

# 检查服务状态
echo "🔍 Checking service health..."
docker-compose -f docker-compose.dev.yml ps

# 等待 PostgreSQL 就绪
echo "⏳ Waiting for PostgreSQL to be ready..."
until docker-compose -f docker-compose.dev.yml exec -T postgres pg_isready -U postgres -d plugin_cloud_dev; do
    echo "Waiting for PostgreSQL..."
    sleep 2
done

# 等待 Redis 就绪
echo "⏳ Waiting for Redis to be ready..."
until docker-compose -f docker-compose.dev.yml exec -T redis redis-cli ping; do
    echo "Waiting for Redis..."
    sleep 2
done

# 生成 Prisma 客户端
echo "🔧 Generating Prisma client..."
cd apps/cloud-platform-api
pnpm db:generate

# 运行数据库迁移
echo "🗄️ Running database migrations..."
pnpm db:push

# 检查是否需要种子数据
if grep -q "DEV_SEED_DATA=true" .env; then
    echo "🌱 Seeding database with development data..."
    # pnpm db:seed  # 暂时注释，等种子脚本创建后启用
fi

echo ""
echo "🎉 Development environment setup complete!"
echo ""
echo "📍 Services:"
echo "   🌐 API Server: http://localhost:3000"
echo "   🗄️ Database (Adminer): http://localhost:8080"
echo "   📊 MinIO Console: http://localhost:9001"
echo "   📧 MailHog: http://localhost:8025"
echo "   📈 Prometheus: http://localhost:9090"
echo "   📊 Grafana: http://localhost:3001"
echo ""
echo "🚀 To start the API server:"
echo "   cd apps/cloud-platform-api"
echo "   pnpm dev"
echo ""
echo "🛑 To stop all services:"
echo "   docker-compose -f docker-compose.dev.yml down"
echo ""
echo "📚 API Documentation: http://localhost:3000/api/v1/docs"
echo "❤️  Health Check: http://localhost:3000/health"
